package myserver;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import myserver.core.Request;
import myserver.core.RequestParser;
import myserver.core.Response;
import myserver.core.ServiceDispatcher;

/**
 * Web Server启动类
 * 
 * 来自文档：https://www.cnblogs.com/xifengxiaoma/p/9451044.html
 * 
 * http://localhost/api/api1
 * http://localhost/api/api2
 * http://localhost/api/api3 无此接口
 * http://localhost/index.html
 */
public class WebServer {
	/**
     * WEB_ROOT是HTML和其它文件存放的目录. 这里的WEB_ROOT为工作目录下的webroot目录
     */
    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
    /**
     * 服务器启动端口
     */
    private int port = 8088;
    /**
     * 服务端Socket
     */
    private ServerSocket serverSocket;
    
    public WebServer() {
        init();
    }
    
    /**
     * 初始化服务端Socket
     */
    private void init() {
        try {
            // 创建服务端Socket
            serverSocket = new ServerSocket(port);
            System.out.println("服务端已启动，等待客户端连接..");
        } catch (IOException e) {
            e.printStackTrace();
        }    
    }

    /**
     * 启动服务器，监听并处理客户请求
     * @throws IOException
     */
    public void start() throws IOException {
        while (true) {
            // 侦听并接受客户请求
            Socket socket = serverSocket.accept();
            // 新启线程，处理客户请求
            new Thread() {
                @Override
                public void run() {
                    service(socket);
                }
            }.start();
        }
    }

    /**
     * 处理客户请求
     * @param socket
     */
    private void service(Socket socket) {
    	System.out.println("接收到客户端连接, " + socket.getInetAddress() + ":" + socket.getPort());
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            // 读取请求信息内容
            Request request = new RequestParser().parse(inputStream);
            Response response = new Response(outputStream);

            service(request, response);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }

    /**
     * 处理客户请求, 把请求交给框架派遣服务，类似Spring的DispatcherServlet
     * @param request
     * @param response
     */
    private void service(Request request, Response response) {
        ServiceDispatcher serviceDispatcher = new ServiceDispatcher();
        serviceDispatcher.dispatcher(request, response);
    }

    public static void main(String[] args) {
        try {
            new WebServer().start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}